package com.ruicar.afs.cloud.manage.creditchange.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.ProcessStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.YesOrNoEnum;
import com.ruicar.afs.cloud.image.config.FileProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.service.ComAttachmentManagementService;
import com.ruicar.afs.cloud.manage.common.entity.ComAttachementFile;
import com.ruicar.afs.cloud.manage.common.entity.ManageBankCardChange;
import com.ruicar.afs.cloud.manage.common.service.ComAttachementFileService;
import com.ruicar.afs.cloud.manage.common.service.ManageBankCardChangeService;
import com.ruicar.afs.cloud.manage.creditchange.condition.ComAttachmentCondition;
import com.ruicar.afs.cloud.manage.creditchange.condition.PermitTemplateCondition;
import com.ruicar.afs.cloud.manage.creditchange.enums.BankTemplatePrintTypeEnum;
import com.ruicar.afs.cloud.manage.creditchange.service.ContractTemplateService;
import com.ruicar.afs.cloud.manage.creditchange.util.TranslateBankCodeUntil;
import com.ruicar.afs.cloud.manage.creditchange.vo.BankApprovalVo;
import com.ruicar.afs.cloud.manage.creditchange.vo.BankCardManageVO;
import com.ruicar.afs.cloud.manage.creditchange.vo.TemplateContractVO;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author chuke
 * @create 2020/8/17 11:35
 */
@Slf4j
@RestController
@RequestMapping("/contractAttach")
@AllArgsConstructor
public class ChangeTemplateController {
    private final ContractTemplateService contractTemplateService;
    private final ComAttachmentFileService attachmentFileService;
    private final FileProperties fileProperties;
    private final ComAttachmentFileService comAttachmentFileService;
    private final ComPrintFormManageService comPrintFormManageService;
    private final ManageBankCardChangeService bankCardChangeService;
    private final ComAttachementFileService comAttachementFileService;
    private final ComAttachmentManagementService comAttachmentManagementService;
    private final ManageBankCardChangeService manageBankCardChangeService;


    @ApiOperation(value = "模板生成")
    @PostMapping("/contractTemplate")
    public IResponse contractTemplate(HttpServletResponse response, @RequestBody BankCardManageVO vo) throws ParseException {
        contractTemplateService.contractTemplate(response, vo);
        return new IResponse().success("模板生成完毕");


    }

    @ApiOperation(value = "模板列表")
    @PostMapping("/getComAttach")
    public IResponse getComAttach(HttpServletResponse response, @RequestBody BankApprovalVo vo) throws ParseException {
        //获取下载的模板id
        String template = contractTemplateService.photoTemplate(vo);
        //模板的业务编号列表
        List caseNoList = new ArrayList();
        //模板生成
        //工商银行新增模板
        ComPrintFormManage icbcId = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>lambdaQuery()
                .eq(ComPrintFormManage::getPrintFormId, "ICBC003"));
        //工商银行新增模板
        ComPrintFormManage icbcDelId = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>lambdaQuery()
                .eq(ComPrintFormManage::getPrintFormId, "ICBC002"));
//        template = String.valueOf(icbcId.getId());
        //新增/删除模板生成 ，工商银行新增模板除外
        if ((vo.getTypeEnum().equals(BankTemplatePrintTypeEnum.INCREASE.name()) &&
                !template.equals(String.valueOf(icbcId.getId())))
                || (vo.getTypeEnum().equals(BankTemplatePrintTypeEnum.DROP.name()) &&
                !template.equals(String.valueOf(icbcDelId.getId())))
        ) {
            vo.setTemplateId(template);
            contractTemplateService.businessTemplate(vo);
           /* for (BankCardManageVO bankCardManageVO : vo.getBankCardManageVOs()) {
                caseNoList.add(bankCardManageVO.getCaseNo());
            }*/
            caseNoList.add(vo.getBankCardManageVOs().get(0).getCaseNo());
        } else {//工商银行新增模板生成
            for (BankCardManageVO bankCardManageVO : vo.getBankCardManageVOs()) {
                bankCardManageVO.setTemplateId(template);
                bankCardManageVO.setTypeEnum(vo.getTypeEnum());
                contractTemplateService.contractTemplate(response, bankCardManageVO);
                caseNoList.add(bankCardManageVO.getCaseNo());
            }
        }
        List<ComAttachmentFile> comAttachList;
        if (vo.getTypeEnum().equals(BankTemplatePrintTypeEnum.PERMIT.name())){
            template = "mergeFile";
            comAttachList = contractTemplateService.getComAttachList(template, caseNoList);
        }else {
            comAttachList = contractTemplateService.getComAttachList(template, caseNoList);
        }
        ComAttachmentCondition condition = new ComAttachmentCondition();
        condition.setAttachmentList(comAttachList);
        return new IResponse().setData(condition);
    }


    /**
     * 批量文件下载
     *
     * @param response
     * @param condition
     */
    @PostMapping("/downBatchFile")
    public void downloadBatchFile(HttpServletResponse response, @RequestBody ComAttachmentCondition condition) {

        // 1-临时目录
        String applyNo = String.valueOf(condition.getAttachmentList().get(0).getId());
        String destPath = fileProperties.getTempDir() + File.separator + applyNo + File.separator + DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumber();
        // 2-远程下载
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", comAttachmentFileService.getAuthorization());
        for (ComAttachmentFile attachmentFile : condition.getAttachmentList()) {
            ComAttachmentFile comAttachmentFile = attachmentFileService.getById(attachmentFile.getId());
            byte[] fileByte = attachmentFileService.downloadAttachmentFile(comAttachmentFile);
            if (fileByte.length > 0) {
                FileUtil.writeBytes(fileByte, destPath + File.separator + attachmentFile.getFileName());
            }
        }
        BufferedInputStream bufferedInputStream = null;
        try {
            String zipFileName = UUID.randomUUID().toString() + ".zip";
            File zipFile = ZipUtil.zip(destPath);
            response.reset(); // 重点突出
            if (FileUtil.exist(destPath)) {
                File file = FileUtil.file(zipFile);
                bufferedInputStream = FileUtil.getInputStream(file);
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;filename=" + HttpUtil.encodeUtf8(zipFileName));
                IoUtil.copy(bufferedInputStream, response.getOutputStream(), 1024);
                response.getOutputStream().flush();
                IoUtil.close(bufferedInputStream);
                //删除打包文件
                FileUtil.del(fileProperties.getTempDir() + File.separator + applyNo);
                return;
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            IoUtil.close(bufferedInputStream);
            FileUtil.del(destPath);
            log.error("文件下载失败:" + e.getMessage());
        } finally {
            IoUtil.close(bufferedInputStream);
        }
    }

    @ApiOperation(value = "影像件模板生成")
    @PostMapping("/photoTemplate")
    public IResponse photoTemplate(HttpServletResponse response, @RequestBody BankCardManageVO vo) throws ParseException {
        contractTemplateService.contractTemplate(response, vo);
        return new IResponse().success("影响件模板生成完毕");
    }

    @ApiOperation(value = "客户打印授权书模板")
    @PostMapping("/printPermitFile")
    public IResponse printPermitFile(@RequestBody BankCardManageVO vo) throws ParseException {
        ManageBankCardChange bankCard = new ManageBankCardChange();
        if (vo.getCaseNo() != null) {
            bankCard = bankCardChangeService.getOne(Wrappers.<ManageBankCardChange>lambdaQuery()
                    .eq(ManageBankCardChange::getCaseNo, vo.getCaseNo()));
        }else {
            bankCard = bankCardChangeService.getById(vo.getId());
        }
        if (bankCard == null) {
            throw new AfsBaseException("请保存后，再进行模板生成");
        }
        if (StringUtils.isEmpty(bankCard.getNewCardholder())) {
            throw new AfsBaseException("新持卡人为空");
        }
        if (StringUtils.isEmpty(bankCard.getNewBank())) {
            throw new AfsBaseException("新银行为空");
        }
        if (StringUtils.isEmpty(bankCard.getNewCardholder())) {
            throw new AfsBaseException("新持卡人为空");
        }
        if (StringUtils.isEmpty(bankCard.getNewBankAccount())) {
            throw new AfsBaseException("新银行卡号为空");
        }
        List<BankCardManageVO> bankCardManageVOS = new ArrayList<>();
        bankCardManageVOS.add(vo);
        BankApprovalVo vos = new BankApprovalVo();
        vos.setTypeEnum(BankTemplatePrintTypeEnum.PERMIT.name());
        vos.setBankCardManageVOs(bankCardManageVOS);
        String template = null;
        switch (vos.getBankCardManageVOs().get(0).getNewBank()) {
            case "137"://工商银行
                ComPrintFormManage icbcId = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>lambdaQuery()
                        .eq(ComPrintFormManage::getPrintFormId, "ICBC001"));
                template = String.valueOf(icbcId.getId());
                break;
            case "101"://中国银行
                ComPrintFormManage bocId = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>lambdaQuery()
                        .eq(ComPrintFormManage::getPrintFormId, "BOC002"));
                template = String.valueOf(bocId.getId());
                break;
            case "524853"://中国建设银行
                ComPrintFormManage ccbId = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>lambdaQuery()
                        .eq(ComPrintFormManage::getPrintFormId, "CCB002"));
                template = String.valueOf(ccbId.getId());
                break;
            case "5500814"://中国邮储银行
                ComPrintFormManage psbcId = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>lambdaQuery()
                        .eq(ComPrintFormManage::getPrintFormId, "PSBC001"));
                template = String.valueOf(psbcId.getId());
                break;
            default:
                break;
        }

        vo.setTemplateId(template);
        //获取下载的模板id
//        String template = contractTemplateService.photoTemplate(vos);
        //模板数据VO
        TemplateContractVO templateVO = new TemplateContractVO();//模板Vo

        templateVO.setCertNo(bankCard.getCertNo());//证件号
        templateVO.setCustName(bankCard.getNewCardholder());//客户名
        if (bankCard.getOldBank().equals(bankCard.getNewBank())) {
            //工商与建设银行，同行变更要填写原账户与账号
            templateVO.setOldBank(bankCard.getOldBank());//原银行
            templateVO.setOldBankAccount(bankCard.getOldBankAccount());//账户号
            templateVO.setOldCardholder(bankCard.getOldCardholder());//账号开户名
            templateVO.setChangeCertNO(bankCard.getCertNo());
            templateVO.setChangeNewBank(TranslateBankCodeUntil.translateBankCode(bankCard.getNewBank()));
        }

        //合同关闭时间+三个月
        if (bankCard.getCloseDate() != null) {
            Calendar endDate = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String timeFormat = sdf.format(bankCard.getCloseDate());
            Date endDatetime = sdf.parse(timeFormat);
            endDate.setTime(endDatetime);
            endDate.add(Calendar.MONTH, 3);
            String defaultEndDate = sdf.format(endDate.getTime());
            templateVO.setCloseDate(DatePattern.CHINESE_DATE_FORMAT.format(sdf.parse(defaultEndDate)));
        }

        templateVO.setApplyNo(bankCard.getApplyNo());
        templateVO.setContactNo(bankCard.getContactNo());
        templateVO.setNewBank(bankCard.getNewBank());//新银行
        templateVO.setNewBankAccount(bankCard.getNewBankAccount());//新银行账户
        templateVO.setNewCardholder(bankCard.getNewCardholder());//新持卡人
        templateVO.setCaseNo(bankCard.getCaseNo());//新持卡人
        templateVO.setSignTime(DatePattern.CHINESE_DATE_FORMAT.format(new Date())); //签署时间
        JSONObject jsonTemp = (JSONObject) JSONObject.toJSON(templateVO);
        //生成之前，删除其他模板
        comAttachementFileService.remove(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, bankCard.getCaseNo())
                .eq(ComAttachementFile::getBusiNo, template));
        comPrintFormManageService.print(jsonTemp, template, bankCard.getCaseNo(), bankCard.getContractNo());

        ComAttachmentCondition conditions = new ComAttachmentCondition();
        List caseNoList = new ArrayList();
        caseNoList.add(bankCard.getCaseNo());
        List<ComAttachmentFile> comAttachList = contractTemplateService.getComAttachList(template, caseNoList);
        conditions.setAttachmentList(comAttachList);

        return new IResponse().setData(conditions);
    }

    @ApiOperation(value = "接收小程序传来的打印模板")
    @PostMapping("/receivePermitFile")
    public IResponse receivePermitFile(@RequestBody ComAttachmentFile file) {
        BankCardManageVO cardManageVO = new BankCardManageVO();
        ComAttachmentManagement comAttachmentManagement = comAttachmentManagementService.getOne(Wrappers.<ComAttachmentManagement>lambdaQuery()
                .eq(ComAttachmentManagement::getBusiNode, "bankCard")
                .eq(ComAttachmentManagement::getAttachmentName, "银行划款授权书"));
        file.setAttachmentCode(String.valueOf(comAttachmentManagement.getId()));
        log.info("文件接收成功");
        comAttachmentFileService.save(file);
        //存完文档后，将业务提交流程
        ManageBankCardChange bankCardParams = manageBankCardChangeService.getOne(Wrappers.<ManageBankCardChange>lambdaQuery()
                .eq(ManageBankCardChange::getCaseNo, file.getBusiNo()));
        BeanUtils.copyProperties(bankCardParams, cardManageVO);
        manageBankCardChangeService.submitBankCardRecord(cardManageVO);
        return new IResponse().setMsg("保存成功");
    }


    @ApiOperation(value = "生成二维码时合成上传文件")
    @PostMapping("/mergeUploadFile")
    public IResponse mergeUploadFile(HttpServletResponse response, @RequestBody BankCardManageVO vo) {
        ComAttachementFile attachementFile = contractTemplateService.mergeUploadFile(response, vo);
        return new IResponse().setData(attachementFile);
    }


}
